import { Module } from 'vuex'
import { ILoginState } from './types'
import { IRootStore } from '../types'
import {
  accountLoginRequest,
  requestUserInfoById,
  requestRoleMenusById
} from '@/service/login/login'
import { IAccount } from '@/service/login/types'
import LocalCache from '@/utils/cache'
import { mapMenusToRoutes, mapMenuToPermissions } from '@/utils/map-menus'
import router from '@/router'

// <S, R>: S模块中state的类型  R->根store中的state的类型
const loginModule: Module<ILoginState, IRootStore> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      userMenus: [],
      permissions: []
    }
  },
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    changeUserMenus(state, userMenus: any) {
      state.userMenus = userMenus

      // 映射该账号下所有路由，动态添加到router的main下面
      const routes = mapMenusToRoutes(userMenus)
      routes.forEach((route) => {
        router.addRoute('main', route)
      })

      // 获取按钮权限数组
      const permissions = mapMenuToPermissions(userMenus)
      state.permissions = permissions
    }
  },
  actions: {
    async accountLoginAction({ commit, dispatch }, payload: IAccount) {
      // 登录
      const loginInfo = await accountLoginRequest(payload)
      const { id, token } = loginInfo.data
      commit('changeToken', token)
      LocalCache.setCache('token', token)

      // 获取部门和角色的下拉项, 主要是调用根store中的action
      dispatch('getEtireDepartment', null, { root: true })

      // 请求用户信息
      const userInfoResult = await requestUserInfoById(id)
      const userInfo = userInfoResult.data
      commit('changeUserInfo', userInfo)
      LocalCache.setCache('tsUserInfo', userInfo)

      // 获取角色
      const userMenuResult = await requestRoleMenusById(userInfo.role.id)
      const userMenus = userMenuResult.data
      commit('changeUserMenus', userMenus)
      LocalCache.setCache('tsUserMenus', userMenus)

      // 跳转到首页
      router.push('/main')
    },
    // 只要是刷新后就从本地缓存中读取信息存入到vuex中
    loadLocalLogin({ commit, dispatch }) {
      const token = LocalCache.getCache('token')
      if (token) commit('changeToken', token)

      // 获取部门和角色的下拉项, 主要是调用根store中的action
      dispatch('getEtireDepartment', null, { root: true })

      const userInfo = LocalCache.getCache('tsUserInfo')
      if (userInfo) commit('changeUserInfo', userInfo)

      const userMenus = LocalCache.getCache('tsUserMenus')
      if (userMenus) commit('changeUserMenus', userMenus)
    },
    phoneLoginAction({ commit }, payload: any) {
      console.log(payload)
      commit('')
    }
  },
  getters: {
    getToken(state) {
      return state.token
    }
  }
}

export default loginModule
